package com.apes.framework.query.lib;

import com.apestech.api.xml.esb.EsbUtil;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.callback.SqlCallback;
import com.apestech.framework.sql.modul.FromList;
import com.apestech.framework.util.StringUtil;

import java.util.ArrayList;

/**
 * @author hup
 * @create 2020-01-17-18:01
 */
public class BaseSqlCallBack extends StringUtil implements SqlCallback {
    @Override
    public String getField(FromList fromtab, String fieldname) throws Exception {
        return fieldname;
    }

    @Override
    public String getChildSelect(String key, String colName, String ftabName, Table ftab) throws Exception {
        String name=key+"_NAME";
        if(StringUtil.rightStr(key,3).equals("_ID")) {
            name = key.substring(0, key.length() - 3) + "_NAME";
            if ("MAS_ENUMERATION".equals(ftabName)) {
                return "(SELECT Z.DESCRIPTION FROM " + ftabName + " Z WHERE A." + key + "=Z." + colName + ") AS " + name;
            } else if ("CRM_CUSTOMER_CAR".equals(ftabName)) {
                return "(SELECT Z.PLATE_NUMBER FROM " + ftabName + " Z WHERE A." + key + "=Z." + colName + ") AS PLATE_NUMBER";
            } else if ("MAS_PARTY_ROLE".equals(ftabName)) {
                return "(SELECT Z2.NAME FROM MAS_PARTY_ROLE Z1, MAS_PARTY Z2 WHERE Z1.PARTY_ID=Z2.ID AND A." + key + "=Z1." + colName + ") AS " + name;
            } else if ("AUT_OPERATIONS".equals(ftabName)) {
                return null;
            }
        }
        return null;
    }

    @Override
    public JSONObject toJSON(FromList tables, JSONObject map) throws Exception {
        if(map==null) return null;
        ArrayList<String> klist=map.getKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            String k=klist.get(i);
            Object value=map.get(k);
            if(value==null) {
                continue;
            }
            //PRODUCT_ID_CLASSIFY_ID
            if(klist.contains(k+"_NAME") || klist.contains(k+"_DESCRIPTION")) {
                JSONObject m1 = new JSONObject();
                m1.put("ID", map.get(k));
                if (klist.contains(k + "_NAME")) {
                    m1.put("NAME", map.get(k + "_NAME"));
                    map.put(k, m1);
                    map.remove(k + "_NAME");
                } else {
                    m1.put("DESCRIPTION", map.get(k + "_DESCRIPTION"));
                    map.put(k, m1);
                    map.remove(k + "_DESCRIPTION");
                }
            } else {
                JSONObject v= EsbUtil.getDownData(k, castToString(value));
                if(v!=null){
                    map.put(k, v);
                }
            }
        }
        return map;
    }

    @Override
    public String getFieldName(FromList tables, String field) throws Exception {
        return field;
    }
}
